package edu.whu.irlab.woscrawl.pubmed;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhongwei on 2017/3/4.
 */
public class SessionCreator extends Thread {

    private Object lock;
    private WebDriver driver;

    public static void main(String[] args) {
        new SessionCreator().start();
    }

    @Override
    public void run() {
        while (true) {
            work();
            try {
                sleep(30 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void work() {
        driver = new ChromeDriver();
        try {
            Search.search(driver);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver.findElement(By.id("s2id_selectSortBy_.bottom")).click();
        Select sort = new Select(driver.findElement(By.id("selectSortBy_.bottom")));
        List<WebElement> sortOptions = sort.getOptions();
        sortOptions.get(3).click();
        driver.findElement(By.id("s2id_selectPageSize_.bottom")).click();
        Select select = new Select(driver.findElement(By.id("selectPageSize_.bottom")));
        List<WebElement> options = select.getOptions();
        options.get(options.size() - 1).click();
        String url = driver.getCurrentUrl();
        Pattern p1 = Pattern.compile("&qid=(.+?)&");
        Pattern p2 = Pattern.compile("&SID=(.+?)&");
        Matcher matcher = p1.matcher(url);
        String qid = "";
        String SID = "";
        if (matcher.find()) {
            qid = matcher.group(1);
        }
        matcher = p2.matcher(url);
        if (matcher.find()) {
            SID = matcher.group(1);
        }
        System.out.println(qid);
        System.out.println(SID);


        for (int i = 1; i <= 45; i++) {
            String content = "";
            File file;
            try {
                file = new File("pubMed/link/linksTo_" + i + ".txt");
                content = FileUtils.readFileToString(file);
                content = content.replaceAll("&qid=\\d{1,5}&", "&qid=" + qid + "&")
                        .replaceAll("&SID=.+?&", "&SID=" + SID + "&")
                        .replaceAll("&parentQid=\\d{1,5}&", "&parentQid=" + qid + "&");
                FileUtils.write(file, content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        driver.quit();
    }
}
